<template>
  <div class="EmergencyList">
    <div class="flex location-wrap">
      <span class="white">当前位置：</span>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/DutyIndex' }">值班管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/EmergencyDailyPlanList' }">应急值班</el-breadcrumb-item>
        <el-breadcrumb-item>计划</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="box">
      <!-- 列表筛选 -->
      <filterTitle @query="query" @reset="reset" @node-click="deptChoose" :form="form" :formData="formData">
      </filterTitle>
      <!-- 列表表格 -->
      <LsdTable slot="gjxm" :paginationAtrrs="paginationAtrrs" @pageChange="handleSizeChange" :compRef="table.compRef"
        ref="gjxm" :columns="table.columns" :title="table.title" :actions="table.actions" :tableData="table.tableData"
        :tableAttr="table.tableAttr" :isShowPage="table.isShowPage" :isSelectFlag="table.isSelectFlag"
        :isSequenceFlag="table.isSequenceFlag" @onActionClick="onActionClick" />
    </div>
    <!-- 值班计划 -->
    <LsdDialog :dialogConfig="add_dialog" @handleBtn="handleAddBtn" @close="close">
      <LsdDialogTitle slot="dialog" :titleConfig="titleConfig" :activeNames="activeNames"
        @getResourcesData="handelDialogTitleBtn">
        <el-form slot="slot0" ref="add_form_0" :model="add_form" label-width="120px" size="small" :rules="add_rules"
          :class="is_preview ? 'is-preview' : ''">
          <el-row>
            <el-col :span="8">
              <el-form-item label="值班类别：" prop="dutyCategory">
                <el-select v-model="add_form.dutyCategory" placeholder="请选择" :popper-append-to-body="false"
                  v-if="!is_preview" key="dutyCategory" @change="dutyCategoryChange">
                  <el-option :label="item.label" :value="item.value" v-for="(item, i) in duty_category_options"
                    :key="i"></el-option>
                </el-select>
                <div class="font-s-16" v-else>{{
                  duty_category_options.filter(item => item.value ==
                    add_form.dutyCategory)[0].label
                }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="信息来源：" prop="dutySourceId">
                <!-- <el-select v-model="add_form.dutySourceId" placeholder="请选择" :popper-append-to-body="false" v-if="!is_preview&&add_form.dutyCategory == 1" key="dutySourceId">
                  <el-option :label="item.warningNoticeName" :value="item.id" v-for="(item, i) in response_options" :key="i"></el-option>
                </el-select> -->
                <el-select v-model="add_form.dutySourceId" placeholder="请选择" :popper-append-to-body="false"
                  v-if="!is_preview" key="dutySourceId">
                  <el-option :label="add_form.dutyCategory == 1 ? item.warningNoticeName : item.responseName"
                    :value="item.id" v-for="(item, i) in response_options" :key="i"></el-option>
                </el-select>
                <div class="font-s-16" v-else>
                  <!-- {{response_options.filter(item => item.id ==add_form.dutySourceId).length && response_options.filter(item => item.id ==add_form.dutySourceId)[0].responseName}} -->
                  {{ add_form.dutySource }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form slot="slot1" ref="add_form" :model="add_form" label-width="120px" size="small" :rules="add_rules"
          :class="is_preview ? 'is-preview' : ''">
          <el-row>
            <el-col :span="15">
              <el-form-item label="值班计划：" prop="dutyPlan">
                <el-input v-model="add_form.dutyPlan" placeholder="请输入值班计划" v-if="!is_preview" key="dutyPlan"></el-input>
                <div class="font-s-16" v-else>{{ add_form.dutyPlan }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="值班地点：" prop="dutyAddress">
                <div class="font-s-16">{{ add_form.dutyAddress }}</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="排班方式：" prop="dutyMode">
                <el-select v-model="add_form.dutyMode" placeholder="请选择排班方式" :popper-append-to-body="false"
                  @change="changeWorkWay" v-if="!is_preview" key="dutyMode">
                  <el-option v-for="item in work_ways" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <div class="font-s-16" v-else>{{ work_ways.filter(item => item.value == add_form.dutyMode)[0].label }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="值班日期：" prop="dates" v-if="add_form.dutyMode == 2" key="1">
                <el-date-picker v-model="add_form.dates" type="daterange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期" value-format="yyyy-MM-dd" :clearable="false" :picker-options="pickerOptions"
                  @change="changeDate" v-if="!is_preview" key="dates">
                </el-date-picker>
                <div class="font-s-16" v-else>{{ add_form.dates[0] }} 至 {{ add_form.dates[1] }}</div>
              </el-form-item>
              <el-form-item label="值班日期：" prop="month" v-else-if="add_form.dutyMode == 1" key="2">
                <el-date-picker v-model="add_form.month" type="month" placeholder="选择月份" value-format="yyyy-MM"
                  :clearable="false" v-if="!is_preview" key="month">
                </el-date-picker>
                <div class="font-s-16" v-else>{{ add_form.dates[0] }} 至 {{ add_form.dates[1] }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="班次设置：" prop="dutyShiftString">
                <el-select v-model="add_form.dutyShiftString" placeholder="请选择" :popper-append-to-body="false"
                  v-if="!is_preview">
                  <el-option v-for="(item, i) in dutyShift_options" :key="i" :label="item.shiftCategory"
                    :value="item.shiftCategory"></el-option>
                </el-select>
                <div class="font-s-16" v-else>{{ add_form.dutyShiftString }}</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="备注：" prop="remark">
              <el-input type="textarea" placeholder="请输入内容" v-model="add_form.remark" resize="none" autosize
                v-if="!is_preview" key="remark">
              </el-input>
              <div class="font-s-16" v-else>{{ add_form.remark }}</div>
            </el-form-item>
          </el-row>
        </el-form>
        <!-- 排班计划表 -->
        <div slot="slot2" class="plan-table-box">
          <el-table :data="createPlanTable" style="width: 100%" :header-cell-style="header_cell_style" border
            max-height="400px" :span-method="dateRowMerge">
            <el-table-column prop="dutyDate" label="值班日期" align="center" width="150">
            </el-table-column>
            <el-table-column prop="shiftName" label="班次名称" align="center" width="150">
            </el-table-column>
            <el-table-column prop="shiftTime" label="班次时间" align="center" width="150">
            </el-table-column>
            <el-table-column label="带班领导" align="center" width="170">
              <template slot-scope="scope">
                <el-select v-model="scope.row.dutyLeadersId" placeholder="请选择" :popper-append-to-body="false"
                  class="duty-leaders" size="small" v-if="!is_preview">
                  <el-option :label="item.realName" :value="item.val" v-for="(item, i) in leader_options"
                    :key="i"></el-option>
                </el-select>
                <span v-else>{{ scope.row.dutyLeadersId.split('+')[0] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="值班主任" align="center" width="200">
              <template slot-scope="scope">
                <span class="blue-text" @click="showPersonDialog(scope.row, scope.$index, 1)" v-if="!is_preview">
                  {{ scope.row.member1.name || '点击选择' }}
                </span>
                <span v-else>{{ scope.row.member1.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="值班员" align="center">
              <template slot-scope="scope">
                <span class="blue-text" v-if="scope.row.member2.length && !is_preview"
                  @click="showPersonDialog(scope.row, scope.$index, 1)">
                  {{ formatName(scope.row.member2) }}
                </span>
                <span v-else>{{ formatName(scope.row.member2) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 创建人 -->
        <div slot="slot3">
          <DialogForm ref="creator" :formConfig="creator_form" />
        </div>
      </LsdDialogTitle>
    </LsdDialog>
    <!-- 人员选择 -->
    <LsdDialog :dialogConfig="person_dialog" @close="closePersonDialog" @handleBtn="handleChangeBtn">
      <Person slot="dialog" ref="Person" :is-show="person_dialog.isShow" :operatorDuty="operatorDuty" :row="person_row">
      </Person>
    </LsdDialog>
    <!-- 人员变更 -->
    <LsdDialog :dialogConfig="change_person_dialog" @handleBtn="handleChangeBtn" @close="closeChangePersonDialog">
      <LsdDialogTitle slot="dialog" :titleConfig="[{ title: '排班计划表', name: '1', slot: 'slot1' }]"
        :activeNames="activeNames">
        <el-table :data="change_person_table" style="width: 100%" :header-cell-style="header_cell_style" border
          max-height="520px" :span-method="dateRowMerge" slot="slot1" cell-class-name="change-person-cell">
          <el-table-column prop="dutyDate" label="值班日期" align="center" width="150">
          </el-table-column>
          <el-table-column prop="shiftName" label="班次名称" align="center" width="150">
          </el-table-column>
          <el-table-column prop="shiftTime" label="班次时间" align="center" width="150">
          </el-table-column>
          <el-table-column label="带班领导" prop="dutyLeadersName" align="center" :show-overflow-tooltip='true'>
          </el-table-column>
          <el-table-column label="值班主任" align="center" :show-overflow-tooltip='true'>
            <template slot-scope="scope">
              {{ scope.row.leaderList[0].name }}
              <img src="../../../../assets/img/u226.png" alt="" class="leave-icon"
                v-if="scope.row.leaderList[0].absenceStatus == 1">
            </template>
          </el-table-column>
          <el-table-column label="值班员" align="center" class-name="staff-col" width="340" :show-overflow-tooltip='true'>
            <template slot-scope="scope">
              <el-row>
                <el-col :span="scope.row.staffList.length == 1 ? 24 : 12" v-for="(item, i) in scope.row.staffList"
                  :key="i">
                  <div class="staff-cell">
                    {{ item.name }}
                    <img src="../../../../assets/img/u226.png" alt="" class="leave-icon" v-if="item.absenceStatus == 1">
                  </div>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="人员变更" align="center" width="160">
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot-scope="scope">
              <img src="../../../../assets/img/u227.png" alt="" class="change-icon"
                @click="showPersonDialog(scope.row, scope.$index, 2)">
              <img src="../../../../assets/img/u226.png" alt="" class="change-icon"
                @click="showLeaveDialog(scope.row, scope.$index, 2)">
            </template>
          </el-table-column>
        </el-table>
      </LsdDialogTitle>
    </LsdDialog>
    <!-- 人员请假 -->
    <LsdDialog :dialogConfig="leave_dialog" @handleBtn="handleLeaveBtn" @close="closeLeaveDialog">
      <div slot="dialog">
        <el-form class="leaveForm" :model="leave_tableForm" ref="leave_tableForm" :rules="leaveRules" size="small">
          <el-table :data="leave_tableForm.tableData" style="width: 100%" :header-cell-style="header_cell_style" border
            max-height="400px" class="leave-table">
            <el-table-column label="计划值班时间" width="180" align="center">
              <template slot-scope="scope">
                <p>{{ scope.row.shiftStartTime }}</p>
                <p>{{ scope.row.shiftEndTime }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="leavePerson" label="请假人" width="180">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.leavePerson'" :rules="leaveRules.leavePerson">
                  <el-select v-model="scope.row.leavePerson" placeholder="请选择" size="small" :popper-append-to-body="false"
                    class="duty-leaders" @focus="leaveChange">
                    <el-option v-for="(item, i) in leave_person_options" :disabled="item.isShow" :key="i"
                      :label="item.name" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="replacePeople" label="替换人" width="180">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.replacePeople'" :rules="leaveRules.replacePeople">
                  <el-select v-model="scope.row.replacePeople" placeholder="请选择" size="small"
                    :popper-append-to-body="false" class="duty-leaders"
                    @focus="substituteChange(scope.$index, scope.row)">
                    <el-option v-for="(item, i) in scope.row.substitute_options" :disabled="item.isShow" :key="i"
                      :label="item.userName" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="请假原因">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.reasonTakingLeave'"
                  :rules="leaveRules.reasonTakingLeave">
                  <el-input v-model="scope.row.reasonTakingLeave" placeholder="请输入内容" size="small"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <div class="operateImg">
                  <img v-show="leave_tableForm.tableData.length == scope.$index + 1"
                    src="../../../../assets/img/listAdd.png" alt="" @click="addLeave" style="margin-right: 10px;">
                  <img src="../../../../assets/img/listReduc.png" alt="" @click="delLeave(scope.$index)">
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </LsdDialog>
    <!-- 导入弹窗 -->
    <el-dialog title="导入历史计划" :visible.sync="importDialog" top="50vh" class="importDialog">
      <el-form :model="importForm" :rules="importRules" label-width="100px" label-position="right" ref="importForm">
        <el-form-item label="值班计划：" prop="id">
          <el-select v-model="importForm.id" placeholder="请选择值班计划">
            <el-option :label="item.dutyPlan" :value="item.id" v-for="item in historyOption" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="footer">
        <el-button type="primary" @click="importSubmit" size="small">确定</el-button>
        <el-button size="small" @click="importDialog = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { formData } from "./config";
import Person from "./components/Person.vue";
import { showTime } from "@/lib";
import { getUntilList } from "@/api/common.js";
import { getPlanListApi, savePlanApi, editPlanApi, submitPlanApi, delPlanApi, getByIdApi, getLeaveDetail, dutyLeave, listPlanDown, changePersonApi, getOrgInfoByOrgId, getDutyDownList } from "@/api/duty/daily/plan.js";
import { getRoleUser } from "@/api/SystemConfig/dutyConfig.js";
import { getpublishedinfo } from "@/api/EmergencyDisposal/xymld.js";
import { listPage } from "@/api/EarlyWarningManagement/yjtzd.js";
import moment from "moment";
export default {
  name: "DailyPlanList",
  components: {
    Person
  },
  data() {
    return {
      type: 1, // 1新增 2编辑
      form: {
        dutyType: "2", // 值班类型;1-日常值班，2-应急值班
        dutyPlan: "",
        createDeptName: "",
        createDeptId: "",
        dutyAddress: "",
        dutyDate: [],
        dutyStartDate: "",
        dutyEndDate: "",
        creator: "",
        createTime: [],
        createStartTime: "",
        createEndTime: "",
        dutyStatus: ""
      },
      formData,
      // 表格信息
      table: {
        isSelectFlag: false, // 是否展示选择器
        compRef: "gjxm",
        isSequenceFlag: true, // 是否展示序号
        isShowPage: true, // 是否展示分页
        resetFlag: true,
        loading: false,
        title: "应急值班计划列表",
        actions: [],
        tableData: [],
        columns: [
          {
            prop: "dutySource",
            label: "信息来源",
            align: "left",
            "width": "340px",
            render: (h, { row }) => {
              return (
                <div>
                  {
                    <span
                      class='commonTableStyle'
                      style='width:100%;'
                      {...{
                        on: {
                          click: () => {
                            this.toResponse(row);
                          }
                        }
                      }}
                    >
                      {row.dutySource}
                    </span>
                  }
                </div>
              );
            }
          },
          {
            prop: "dutyPlan",
            label: "值班计划",
            align: "center",
            "width": "300px",
            render: (h, { row }) => {
              return (
                <div>
                  {
                    <span
                      class='commonTableStyle'
                      style='width:100%;'
                      {...{
                        on: {
                          click: () => {
                            this.onPreview(row.id);
                          }
                        }
                      }}
                    >
                      {row.dutyPlan}
                    </span>
                  }
                </div>
              );
            }
          },
          {
            prop: "createDeptName",
            label: "所属单位",
            align: "center",
            "width": "190px"
          },
          {
            prop: "dutyAddress",
            label: "值班地点",
            align: "center",
            "width": "280px"
          },
          {
            prop: "createTime1",
            label: "值班日期",
            align: "left",
            "width": "210px",
            formatter: (row, column, cellValue, index) => {
              return `${row.dutyStartDate}至${row.dutyEndDate}`;
            }
          },
          {
            prop: "creator",
            label: "创建人",
            align: "center"
          },
          {
            prop: "createTime",
            label: "创建时间",
            align: "left",
            "width": "180px"
          },
          {
            prop: "dutyStatus",
            label: "状态",
            align: "center",
            "width": "100px",
            formatter: (row, column, cellValue, index) => {
              if (row.dutyStatus == "0") {
                return "未发布";
              } else {
                return "已发布";
              }
            }
          },
          {
            prop: "cz",
            label: "操作",
            align: "center",
            fixed: "right",
            "width": "200px",
            render: (h, scope) => {
              let arr = [];
              const roleCode = JSON.parse(sessionStorage.getItem("role")).roleCode;
              const orgId = JSON.parse(sessionStorage.getItem("org")).orgId;
              if (roleCode.indexOf("operator_director") != -1 && scope.row.createDeptId == orgId) {
                if (scope.row.dutyStatus == "0") arr = ["编辑", "人员变更", "删除"];
                else arr = ["人员变更"];
              }
              return (
                <div>
                  {
                    arr.map(item => {
                      return (
                        <span style='color:#3561fd;cursor:pointer;margin:0 10px' {...{
                          on: {
                            click: () => {
                              this.actionHandle(item, scope);
                            }
                          }
                        }}>
                          {item}
                        </span>
                      );
                    })
                  }
                </div>
              );
            }
          }
        ],
        // 表格样式
        tableAttr: {
          stripe: false,
          border: true,
          fit: true,
          "show-header": true,
          "highlight-current-row": true,
          "cell-style": {
            "font-size": "16px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            border: "1px solid #ccc",
            "font-size": "16px"
          }
        }
      },
      // 分页信息
      paginationAtrrs: {
        total: 0,
        "background": true,
        layout: "prev, pager, next",
        "current-page": 1,
        "page-size": 10
        // "page-sizes": [10, 20, 30, 40, 50, 100]
      },
      pageNum: 1,
      pageSize: 10,
      // 新增/编辑dialog
      add_dialog: {
        title: "应急值班计划",
        isShow: false, // 弹窗显示隐藏
        btnList: []
      },
      dutyBtnList: [{
        name: "提交",
        id: "submitBut", // 事件名
        type: "primary",
        size: "small"
      },
      {
        name: "保存",
        id: "saveBut", // 事件名
        size: "small"
      },
      {
        name: "取消",
        id: "cancelBtn",
        size: "small"
      }],
      // 折叠面板信息
      titleConfig: [
        {
          title: "信息来源",
          name: "0",
          slot: "slot0"
        },
        {
          title: "基本信息",
          name: "1",
          slot: "slot1"
        },
        {
          title: "排班计划表",
          name: "2",
          slot: "slot2",
          level: JSON.parse(sessionStorage.getItem("org")).level,
          btnList: [
            {
              name: "循环排班",
              type: "primary",
              size: "mini",
              id: 1
            },
            {
              name: "导入计划",
              type: "primary",
              size: "mini",
              id: 2
            }
          ]
        },
        {
          title: "创建信息",
          name: "3",
          slot: "slot3"
        }
        // {
        //   title: "审批信息",
        //   name: "4",
        //   slot: "slot4"
        // }
      ],
      activeNames: ["0", "1", "2", "3", "4"], // 折叠面板默认展开列
      // 新增/编辑表单
      add_form: {
        id: "",
        dutyType: "2", // 1日常 2应急
        dutyCategory: "1", // 值班类别来源;1-应急值班，2-处置值班
        dutySource: "", // 信息来源
        dutySourceId: "",
        dutyPlan: "", // 值班计划名
        dutyAddress: "", // 值班地点
        dutyMode: 1, // 排班方式 1月 2自定义
        dates: [], // 值班日期
        month: "", // 值班日期 月
        dutyStartDate: "", // 值班开始日期
        dutyEndDate: "", // 值班结束日期
        // dutyShift: 2, // 班次设置
        dutyShiftString: "",
        remark: "", // 备注
        dutyPlanSaveList: [] // 计划表
      },
      // 新增/编辑表单规则
      add_rules: {
        dutyCategory: [
          { required: true, message: "请选择值班类别", trigger: "change" }
        ],
        dutySourceId: [
          { required: true, message: "请选择信息来源", trigger: "change" }
        ],
        source: [
          { required: true, message: "请选择信息来源", trigger: "change" }
        ],
        dutyPlan: [
          { required: true, message: "请输入值班计划", trigger: "blur" }
        ],
        dutyMode: [
          { required: true, message: "请选择排班方式", trigger: "change" }
        ],
        dates: [
          { required: true, message: "请选择值班日期", trigger: "change" }
        ],
        month: [
          { required: true, message: "请选择值班日期", trigger: "change" }
        ],
        dutyShiftString: [
          { required: true, message: "请选择班次", trigger: "change" }
        ]
      },
      // 值班类型
      duty_category_options: [
        {
          label: "预警",
          value: "1"
        },
        {
          label: "处置",
          value: "2"
        }
      ],
      // 信息来源options
      response_options: [],
      // 排班方式options
      work_ways: [
        {
          label: "按月排班",
          value: 1
        },
        {
          label: "自定义排班",
          value: 2
        }
      ],
      // 班次设置
      shiftOptions: [],
      dutyShift_options: [],
      // 排班计划表
      plan_table: [],
      header_cell_style: {
        textAlign: "center",
        backgroundColor: "#B1C8F9",
        border: "1px solid #ccc",
        fontSize: "16px",
        color: "#333"
      },
      // 人员库dialog
      person_dialog: {
        title: "应急值班人员库",
        isShow: false,
        btnList: [
          {
            name: "确认",
            id: "confirmPerson", // 事件名
            type: "primary",
            size: "small"
          },
          {
            name: "取消",
            id: "cancelPerson",
            size: "small"
          }
        ]
      },
      // 所选人员行
      person_row: {},
      // 人员变更dialog
      change_person_dialog: {
        title: "人员变更",
        isShow: false,
        width: "70%",
        btnList: [
          {
            name: "确认",
            id: "changeConfirm", // 事件名
            type: "primary",
            size: "small"
          },
          {
            name: "取消",
            id: "changeCancel",
            size: "small"
          }
        ]
      },
      personDialogId: "",
      operatorDuty: {
        dutyMember1: [],
        dutyMember2: []
      },
      // 值班日期
      choiceDate: "",
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate = minDate.getTime();
          if (maxDate) {
            this.choiceDate = "";
          }
        },
        disabledDate: (time) => {
          if (this.choiceDate) {
            // const { dutyMode } = this.add_form;
            // const one = dutyMode == 1 ? 30 * 24 * 3600 * 1000 : 7 * 24 * 3600 * 1000;
            // const minTime = this.choiceDate - one;
            const minTime = this.choiceDate;
            // const minTime = Date.now() - 8.64e7;
            // const maxTime = this.choiceDate + one;
            // return time.getTime() < minTime || time.getTime() > maxTime;
            return time.getTime() < minTime;
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        }
      },
      // 值班计划表row索引
      plan_table_index: "",
      // 请假dialog
      leave_dialog: {
        title: "人员变更",
        isShow: false,
        btnList: [
          {
            name: "确认",
            id: "confirmLeave", // 事件名
            type: "primary",
            size: "small"
          },
          {
            name: "取消",
            id: "cancelLeave",
            size: "small"
          }
        ]
      },
      // 请假table
      leave_tableForm: {
        tableData: []
      },
      leave_table_data: {
        dutyId: "",
        leavePerson: "",
        reasonTakingLeave: "",
        replacePeople: "",
        shiftStartTime: "",
        shiftEndTime: ""
      },
      leaveRules: {
        leavePerson: [{ required: true, message: "请选择请假人", trigger: "blur" }],
        replacePeople: [{ required: true, message: "请选择替换人", trigger: "blur" }],
        reasonTakingLeave: [{ required: true, message: "请输入请假原因", trigger: "blur" }]
      },
      // 请假人员选项
      leave_options: [],
      leave_person_options: [],
      substitute_options: [],
      // 填报人
      creator_form: {
        formData: [
          {
            type: "input",
            label: "创建人",
            prop: "creator",
            class: "third",
            lableWidth: "120px",
            isDisabled: true
          },
          {
            type: "input",
            label: "单位及部门",
            prop: "createDeptName",
            class: "third",
            lableWidth: "110px",
            isDisabled: true
          },
          {
            type: "input",
            label: "创建时间",
            prop: "createTime",
            class: "third",
            lableWidth: "120px",
            isDisabled: true
          }
        ]
      },
      is_agree: null, // 1同意 2驳回
      // 人员变更table
      change_person_table: [],
      // 是否为变更人员操作
      isChangePerson: null,
      // 是否预览
      is_preview: false,
      // 带班领导options
      leader_options: [],
      // 导入dialog
      importDialog: false,
      importForm: {
        id: ""
      },
      importRules: {
        id: { required: true, message: "请选择值班计划", trigger: "change" }
      },
      historyOption: []
    };
  },
  mounted() {
    if (this.getCreator.role.roleCode.indexOf("operator_staff") != -1) {
      this.table.actions.push({
        id: "addDialogShow",
        text: "新增",
        type: "primary",
        isShow: true,
        btnAttr: { size: "small" }
      });
    }
    this.getOrgTree();
    // this.getPublishedResponse();
    // this.getDutyDownList(); // 获取班次下拉选项
    this.getUsers();
    this.list();
  },
  computed: {
    // 创建计划表
    createPlanTable() {
      const { dates, dutyMode, dutyShiftString, month } = this.add_form;
      let all_days = [];
      let arr = [];
      if ((dates.length || month) && dutyMode && dutyShiftString) {
        const days = this.shiftOptions.find(item => item.shiftCategory == dutyShiftString);
        const dutyShiftList = days.child;
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.6)",
          customClass: "loading-z-index"
        });
        if (dutyMode == 1) {
          // 月排班
          all_days = this.getDayAllByMonth(month);
        } else {
          // 自定义排班
          all_days = this.getDayAll(dates[0], dates[1]);
        }
        for (let i = 0; i < dutyShiftList.length; i++) {
          const projectList = all_days.map(item => {
            return {
              id: "",
              dutyDate: item,
              dutyTimestamp: new Date(item).getTime(),
              shiftName: dutyShiftList[i].shiftName,
              shiftTime: dutyShiftList[i].shiftTime,
              member1: {},
              member2: [],
              shiftStartTime: dutyShiftList[i].shiftTime.split("-")[0],
              shiftEndTime: dutyShiftList[i].shiftTime.split("-")[1]
            };
          });
          arr = arr.concat(projectList);
        }
        arr = arr.sort((a, b) => {
          return new Date(a.dutyDate).getTime() - new Date(b.dutyDate).getTime();
        });
        loading.close();
      }
      return arr;
    },
    getCreator() {
      const account = sessionStorage.getItem("account");
      const org = sessionStorage.getItem("org");
      const role = sessionStorage.getItem("role");
      return {
        name: (account && JSON.parse(account).realName) || "",
        dept: (org && JSON.parse(org).orgName) || "",
        role: (role && JSON.parse(role)) || {},
        org: (org && JSON.parse(org)) || {},
        unitName: (org && JSON.parse(org).unitName) || ""
      };
    }
  },
  watch: {
    is_preview(val) {
      if (val) {
        this.titleConfig[2].btnList = [];
      } else {
        this.titleConfig[2].btnList = [
          {
            name: "循环排班",
            type: "primary",
            size: "mini",
            id: 1
          },
          {
            name: "导入计划",
            type: "primary",
            size: "mini",
            id: 2
          }
        ];
      }
    }
  },
  methods: {
    // 列表表格按钮事件
    actionHandle(item, scope) {
      if (item === "编辑") {
        this.onEdit(scope.row.id);
      } else if (item === "删除") {
        this.onDelPlan(scope.row.id);
      } else if (item === "人员变更") {
        this.personDialogId = scope.row.id;
        this.showChangePersonDialog(scope.row.id);
      }
    },
    // 获取全部带班领导
    async getUsers() {
      const res = await getRoleUser({ orgId: this.getCreator.org.orgId, planRoleName: "带班领导" });
      if (res) {
        res.forEach(item => {
          item.val = item.realName + "+" + item.userId;
        });
        this.leader_options = res;
      }
    },
    // 值班类别监听
    dutyCategoryChange() {
      this.response_options = [];
      this.add_form.dutySourceId = "";
      this.getPublishedResponse();
    },
    // 获取已发布的预警通知单/响应命令单
    getPublishedResponse() {
      if (this.add_form.dutyCategory == 1) {
        console.log("dutyCategory", this.add_form.dutyCategory);
        listPage({ noticeState: "3" }).then(res => {
          this.response_options = res.data;
          console.log("预警res", res.data);
        });
      } else {
        getpublishedinfo({}).then(res => {
          this.response_options = res;
          console.log("处置res", res);
        });
      }

    },
    // 获取单位组织结构树
    async getOrgTree() {
      const res = await getUntilList({ orgId: this.getCreator.org.orgId });
      if (res) {
        this.formData[2].treeData.attrs.data = res;
      }
    },
    // 单位部门选择
    deptChoose(val, item) {
      this.form.createDeptName = val[0].orgName;
      this.form.createDeptId = val[0].id;
    },
    // 重置
    reset() {
      this.form = this.$options.data().form;
      this.list();
    },
    // 检索
    query() {
      this.list();
    },
    async list() {
      const parmas = JSON.parse(JSON.stringify(this.form));
      parmas.dutyStartDate = this.form.dutyDate.length ? this.form.dutyDate[0] : "";
      parmas.dutyEndDate = this.form.dutyDate.length ? this.form.dutyDate[1] : "";
      parmas.createStartTime = this.form.createTime.length ? this.form.createTime[0] : "";
      parmas.createEndTime = this.form.createTime.length ? this.form.createTime[1] : "";
      parmas.pageNum = this.pageNum;
      parmas.pageSize = this.pageSize;
      // console.log(parmas);
      const res = await getPlanListApi(parmas);
      this.table.tableData = res.data;
      this.paginationAtrrs.total = res.total;
      this.pageNum = res.pageNum;
    },
    // 分页
    handleSizeChange(val) {
      this.pageNum = val["current-page"];
      this.pageSize = val["page-size"];
      this.list();
    },
    // 列表按钮
    onActionClick(item, index) {
      this[item.id](); // 调用按钮对应方法
    },
    // 新增按钮操作
    addDialogShow() {
      this.getPublishedResponse();
      this.getDutyDownList(); // 获取班次下拉选项
      this.add_form = this.$options.data().add_form;
      this.type = 1;
      this.add_dialog.btnList = this.dutyBtnList;
      this.add_dialog.isShow = true;
      this.$nextTick(() => {
        this.getOrgInfoByOrgId();
        this.$set(this.$refs.creator.form, "creator", this.getCreator.name);
        this.$set(this.$refs.creator.form, "createDeptName", sessionStorage.getItem("dwbmName"));
        this.$set(this.$refs.creator.form, "createTime", showTime(new Date()));
      });
    },
    async getOrgInfoByOrgId() {
      const res = await getOrgInfoByOrgId({ orgId: this.getCreator.org.orgId });
      if (res) {
        this.add_form.dutyAddress = res.dutyAddress;
      }
    },
    // 新增/编辑弹窗按钮操作
    handleAddBtn(item) {
      console.log(item);
      this[item.id]();
    },
    // 关闭新增/编辑弹窗
    close() {
      this.is_agree = null;
      this.$refs.add_form_0.resetFields();
      this.$refs.add_form.resetFields();
      this.$nextTick(() => {
        this.add_dialog.isShow = false;
        this.is_preview = false;
      });
    },
    // 编辑计划
    onEdit(id) {
      this.type = 2;
      this.add_dialog.btnList = this.dutyBtnList;
      this.getById(id, true);
    },
    async getById(id, type) {
      const res = await getByIdApi({ id });
      this.add_dialog.isShow = true;
      res.month = res.dutyStartDate.slice(0, 7);
      res.dates = [res.dutyStartDate.slice(0, 10), res.dutyEndDate.slice(0, 10)];
      this.$nextTick(() => {
        const { dutyPlanVoList, ...formData } = res;
        if (type) this.add_form = formData;
        dutyPlanVoList && dutyPlanVoList.forEach((item, i) => {
          if (this.createPlanTable[i]) {
            if (type) this.createPlanTable[i].id = item.id;
            this.createPlanTable[i].member1 = item.leaderList[0] || {};
            this.createPlanTable[i].member2 = item.staffList || [];
            this.createPlanTable[i].dutyLeadersId = item.dutyLeadersName + "+" + item.dutyLeadersId;
          }
        });
        this.$set(this.$refs.creator.form, "creator", res.creator);
        this.$set(this.$refs.creator.form, "createDeptName", res.createDeptName);
        this.$set(this.$refs.creator.form, "createTime", res.createTime);
      });
    },
    async getDutyDownList() {
      const res = await getDutyDownList();
      if (res) {
        const dataInfo = {};
        res.forEach((item, index) => {
          const { shiftCategory } = item;
          if (!dataInfo[shiftCategory]) {
            dataInfo[shiftCategory] = {
              shiftCategory,
              child: []
            };
          }
          dataInfo[shiftCategory].child.push(item);
        });
        const data = Object.values(dataInfo).filter(item => item.shiftCategory.indexOf(this.getCreator.dept) != -1);
        this.shiftOptions = Object.values(dataInfo);
        this.dutyShift_options = data;
      }
    },
    // 删除计划
    async onDelPlan(id) {
      try {
        await delPlanApi(id);
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.list();
        // eslint-disable-next-line no-empty
      } catch (error) { }
    },
    // 获取值班计划数据
    getParams() {
      const { dutyMode, month, dates } = this.add_form;
      const plan_table = JSON.parse(JSON.stringify(this.createPlanTable));
      const is_all_leader = plan_table.every(item => item.dutyLeadersId);
      const is_all_director = plan_table.every(item => item.member1.id);
      if (!is_all_leader) {
        this.$message.error("带班领导为必选项");
        return;
      }
      if (!is_all_director) {
        this.$message.error("值班主任为必选项");
        return;
      }
      const dutyPlanSaveList = plan_table.map(item => {
        const addDate = moment(item.dutyDate).add(1, "day").format("YYYY-MM-DD");
        return {
          id: item.id,
          dutyDate: new Date(item.dutyDate).getTime(),
          shiftName: item.shiftName,
          shiftTime: item.shiftTime,
          dutyLeadersId: item.dutyLeadersId.split("+")[1],
          dutyLeadersName: item.dutyLeadersId.split("+")[0],
          dutyDirectorId: item.member1.id,
          dutyDirectorName: item.member1.name,
          dutyPersonId: item.member2.map(item => item.id).join(","),
          dutyPersonName: item.member2.map(item => item.name).join(","),
          shiftStartTime: new Date(item.dutyDate + " " + item.shiftStartTime).getTime(),
          shiftEndTime: new Date((item.shiftEndTime == "00:00" ? addDate : item.dutyDate) + " " + item.shiftEndTime).getTime()
        };
      });
      this.add_form.dutyPlanSaveList = dutyPlanSaveList;
      let all_days = [];
      if (dutyMode == 1) {
        all_days = this.getDayAllByMonth(month);
      } else if (dutyMode == 2) {
        all_days = dates;
      }
      this.add_form.dutyStartDate = new Date(`${all_days[0]} 00:00:00`).getTime();
      this.add_form.dutyEndDate = new Date(`${all_days[all_days.length - 1]} 00:00:00`).getTime();
      if (this.add_form.dutyCategory == 1) {
        const filter_duty_source = this.response_options.filter(item => item.id == this.add_form.dutySourceId);
        this.add_form.dutySource = filter_duty_source.length && filter_duty_source[0].warningNoticeName;
      } else if (this.add_form.dutyCategory == 2) {
        const filter_duty_source = this.response_options.filter(item => item.id == this.add_form.dutySourceId);
        this.add_form.dutySource = filter_duty_source.length && filter_duty_source[0].responseName;
      }
      return Object.assign({}, this.add_form, this.$refs.creator.form);
    },
    // 新增弹窗/编辑弹窗  提交
    async submitBut() {
      const validate_1 = await this.$refs.add_form_0.validate();
      const validate_2 = await this.$refs.add_form.validate();
      if (validate_1 && validate_2) {
        try {
          const params = this.getParams();
          if (!params) return;
          params.dutyStatus = 1;
          await submitPlanApi(params);
          this.$message({ message: "提交成功", type: "success" });
          this.close();
          this.list();
        } catch (error) {
          console.error(error);
        }
      } else {
        return false;
      }
    },
    // 新增弹窗/编辑弹窗  保存
    saveBut() {
      this.$refs.add_form.validate(async (valid) => {
        if (valid) {
          try {
            const params = this.getParams();
            params.dutyStatus = 0;
            if (this.type == 1) {
              await savePlanApi(params);
            } else {
              await editPlanApi(params);
            }
            this.$message({ message: "保存成功", type: "success" });
            this.close();
            this.list();
          } catch (error) {
            console.error(error);
          }
        }
      });
    },
    // 新增/编辑取消
    cancelBtn() {
      this.close();
    },
    // 切换排班方式
    changeWorkWay(val) {
      // console.log(val);
      this.add_form.dates = [];
      this.add_form.month = "";
    },
    // 计划表操作按钮组
    handelDialogTitleBtn(res) {
      if (this.add_form.dutyShiftString && this.createPlanTable.length > 0) {
        const { id } = res;
        if (id == 1) {
          this.circulateScheduling();
        } else {
          // 导入
          this.$refs.add_form.validateField("month",
            (valid) => {
              if (!valid) {
                listPlanDown({ type: 2, dutyShift: this.add_form.dutyShiftString, unitId: this.getCreator.org.orgId }).then(res => {
                  if (res) {
                    this.historyOption = res;
                    this.importDialog = true;
                  }
                });

              }
            });
        }
      }
    },
    // 循环排班
    circulateScheduling() {
      // 循环排班
      const days = this.dutyShift_options.find(item => item.shiftCategory == this.add_form.dutyShiftString);
      const planData = JSON.parse(JSON.stringify(this.createPlanTable)).splice(0, days.child.length);
      const member1_arr = [];// 值班主任
      const member2_arr = [];// 值班员
      const duty_leader_arr = [];// 带班领导
      planData.forEach(item => {
        if (item.member1.name) {
          member1_arr.push(item.member1);
        }
        if (item.member2.length) {
          member2_arr.push(item.member2);
        }
        if (item.dutyLeadersId) {
          duty_leader_arr.push(item.dutyLeadersId);
        }
      });
      if (duty_leader_arr.length == days.child.length && member1_arr.length == days.child.length && member2_arr.length == days.child.length) {
        this.createPlanTable.forEach((item, i) => {
          if (!item.member1.name) {
            item.member1 = member1_arr[i % member1_arr.length];
          }
          if (!item.member2.name) {
            item.member2 = member2_arr[i % member2_arr.length];
          }
          if (!item.dutyLeadersId) {
            item.dutyLeadersId = duty_leader_arr[i % duty_leader_arr.length];
          }
        });
      }
    },
    // 导入弹窗
    importSubmit() {
      this.$refs.importForm.validate(async valid => {
        if (valid) {
          this.getById(this.importForm.id, false);
          this.importDialog = false;
        }
      });
    },
    // 人员确认选择
    confirmPerson(res) {
      const member1 = JSON.parse(JSON.stringify(this.$refs.Person.selected_member1));
      const member2 = this.$refs.Person.selected_member2;
      if (!member1.name) {
        this.$message.error("请选择值班长");
        return;
      }
      if (!member2.length) {
        this.$message.error("请选择值班员");
        return;
      }
      this.person_dialog.isShow = false;
      if (this.isChangePerson == 2) {
        // 变更人员
        const obj = Object.assign(this.person_row, { member1 }, { member2 });
        obj.dutyDirectorId = member1.id;
        obj.dutyDirectorName = member1.name;
        obj.dutyPersonId = member2.map(item => item.id).join(",");
        obj.dutyPersonName = member2.map(item => item.name).join(",");
        obj.leaderList = [member1];
        obj.staffList = member2;
        obj.dutyDate = new Date(obj.dutyDate).getTime();
        obj.shiftStartTime = new Date(obj.shiftStartTime).getTime();
        obj.shiftEndTime = new Date(obj.shiftEndTime).getTime();
        changePersonApi(obj).then(res => {
          this.showChangePersonDialog(this.personDialogId);
        });
      } else {
        this.createPlanTable[this.plan_table_index].member1 = member1;
        this.createPlanTable[this.plan_table_index].member2 = member2;
      }
    },
    // 格式化人名
    formatName(arr) {
      return arr.map(item => item.name).join("、");
    },
    // 人员取消选择
    cancelPerson() {
      this.closePersonDialog();
    },
    // 选择值班日期
    changeDate(val) {
      // console.log(val);
      if (!val) {
        this.choiceDate = "";
      }
    },
    // 获取两个日期之间的所有日期
    getDayAll(starDay, endDay) {
      const arr = [];
      const dates = [];
      // 设置两个日期UTC时间
      const db = new Date(starDay);
      const de = new Date(endDay);
      // 获取两个日期GTM时间
      const s = db.getTime() - 24 * 60 * 60 * 1000;
      const d = de.getTime() - 24 * 60 * 60 * 1000;
      // 获取到两个日期之间的每一天的毫秒数
      for (let i = s; i <= d;) {
        i = i + 24 * 60 * 60 * 1000;
        arr.push(parseInt(i));
      }
      // 获取每一天的时间  YY-MM-DD
      for (const j in arr) {
        const time = new Date(arr[j]);
        const year = time.getFullYear(time);
        const mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ("0" + (time.getMonth() + 1));
        const day = time.getDate() >= 10 ? time.getDate() : ("0" + time.getDate());
        const YYMMDD = year + "-" + mouth + "-" + day;
        dates.push(YYMMDD);
      }
      return dates;
    },
    // 获取传入月份内的所有日期 month: 2023-1
    getDayAllByMonth(month) {
      const date = new Date(month);
      const y = date.getFullYear();
      const m = date.getMonth() + 1;
      const day = new Date(y, m, 0);
      const lastday = day.getDate();
      const first = `${y}-${m}-1`;
      const last = `${y}-${m}-${lastday}`;
      const res = this.getDayAll(first, last);
      return res;
    },
    // 排班计划表日期合并
    dateRowMerge({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        let tables = [];
        if (this.change_person_dialog.isShow) {
          tables = this.change_person_table;
        } else {
          tables = this.createPlanTable;
        }
        const _row = this.rowMerge(tables, "dutyDate")[rowIndex];
        const _col = _row > 0 ? 1 : 0;

        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
    // 合并操作
    rowMerge(data, field) {
      const spanArr = [];
      let pos = 0;
      for (let i = 0; i < data.length; i++) {
        if (i == 0) {
          spanArr.push(1);
          pos = 0;
        } else if (data[i][field] === data[i - 1][field]) {
          spanArr[pos] += 1;
          spanArr.push(0);
        } else {
          spanArr.push(1);
          pos = i;
        }
      }
      return spanArr;
    },
    // show值班人员库dialog
    showPersonDialog(row, rowIndex, isChangePerson) {
      this.createPlanTable.forEach(item => {
        if (item.dutyDate == row.dutyDate && item.shiftTime != row.shiftTime) {
          if (item.member1.name) this.operatorDuty.dutyMember1.push(item.member1.id);
          const data = item.member2.map(item => item.id);
          this.operatorDuty.dutyMember2 = this.operatorDuty.dutyMember2.concat(data);
        }
      });
      this.plan_table_index = rowIndex;
      this.person_row = JSON.parse(JSON.stringify(row));
      this.person_dialog.isShow = true;
      this.isChangePerson = isChangePerson;
    },
    // close值班人员库dialog
    closePersonDialog() {
      this.person_dialog.isShow = false;
      this.plan_table_index = "";
      this.person_row = {};
      this.isChangePerson = null;
      this.operatorDuty = {
        dutyMember1: [],
        dutyMember2: []
      };
    },
    // show人员变更dialog
    async showChangePersonDialog(id) {
      const res = await getByIdApi({ id });

      const { dutyPlanVoList } = res;

      this.change_person_table = dutyPlanVoList && dutyPlanVoList.map(item => {
        return {
          ...item,
          member1: item.leaderList[0],
          member2: item.staffList
        };
      });
      this.change_person_dialog.isShow = true;
    },
    // close人员变更dialog
    closeChangePersonDialog() {
      this.change_person_dialog.isShow = false;
      this.change_person_table = [];
    },
    handleChangeBtn(item) {
      this[item.id]();
    },
    // 更换人员确认
    changeConfirm() {
      this.closeChangePersonDialog();
    },
    changeCancel() {
      this.closeChangePersonDialog();
    },
    // show请假dialog
    async showLeaveDialog(row, index) {
      this.leave_tableForm.tableData.length = 0;
      const res = await getLeaveDetail({ unitId: row.createDeptId }) || [];
      this.substitute_options = res;
      this.leave_table_data.shiftStartTime = row.shiftStartTime;
      this.leave_table_data.shiftEndTime = row.shiftEndTime;
      this.leave_table_data.dutyId = row.id;
      this.leave_tableForm.tableData.push(JSON.parse(JSON.stringify(this.leave_table_data)));
      let options = [];
      this.change_person_table.forEach(item => {
        if (item.dutyDate == row.dutyDate) {
          options = options.concat(item.staffList, item.leaderList);
        }
      });
      this.leave_options = options;
      this.leave_options.forEach(item => {
        item.value = item.id + "+" + item.name + "+" + item.role;
      });
      this.leave_person_options = JSON.parse(JSON.stringify(this.leave_options));
      this.leave_dialog.isShow = true;
    },
    // 添加请假人
    addLeave() {
      this.leave_tableForm.tableData.push(JSON.parse(JSON.stringify(this.leave_table_data)));
    },
    // 删除请假人
    delLeave(index) {
      this.leave_tableForm.tableData.splice(index, 1);
    },
    getSubstitute(arr) {
      const options = [];
      this.substitute_options.forEach(item => {
        if (arr.includes(item.roleCode)) {
          item.value = item.userId + "+" + item.userName;
          options.push(item);
        }
      });
      return options;
    },
    getOptions(data, key) {
      const arr = [];
      this.leave_tableForm.tableData.forEach(item => {
        if (item[key]) {
          arr.push(item[key]);
        }
      });
      data.forEach((item, i) => {
        if (arr.includes(item.value)) {
          this.$set(item, "isShow", true);
        } else {
          this.$set(item, "isShow", false);
        }
      });

    },
    leaveChange() {
      this.getOptions(this.leave_person_options, "leavePerson");
    },
    substituteChange(index, row) {
      if (row.leavePerson) {
        const str = row.leavePerson.split("+")[2];
        const options = this.getSubstitute([str]);
        this.getOptions(options, "replacePeople");
        const data = row;
        data.substitute_options = options;
        this.$set(this.leave_tableForm.tableData, index, data);
      } else {
        row.substitute_options = [];
      }
    },
    // close请假dialog
    closeLeaveDialog() {
      this.leave_dialog.isShow = false;
      this.leave_table = this.$options.data().leave_table;
    },
    handleLeaveBtn(item) {
      this[item.id]();
    },
    // 确认请假
    confirmLeave() {
      try {
        this.$refs.leave_tableForm.validate(async valid => {
          if (valid) {
            const params = this.leave_tableForm.tableData.map(item => {
              const leaveStr = item.leavePerson;
              const replaceStr = item.replacePeople;
              return {
                leavePerson: leaveStr.split("+")[1],
                leavePersonId: leaveStr.split("+")[0],
                replacePeople: replaceStr.split("+")[1],
                replacePeopleId: replaceStr.split("+")[0],
                reasonTakingLeave: item.reasonTakingLeave,
                dutyDate: item.shiftStartTime + "-" + item.shiftEndTime,
                id: item.dutyId,
                roleCode: leaveStr.split("+")[2]
              };
            });
            const res = await dutyLeave(params);
            if (res) {
              this.$message({
                message: "提交成功",
                type: "success"
              });
              this.showChangePersonDialog(this.personDialogId);
              this.closeLeaveDialog();
            }
          }
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 取消请假
    cancelLeave() {
      this.closeLeaveDialog();
    },
    // 预览计划
    onPreview(id) {
      this.getDutyDownList(); // 获取班次下拉选项
      this.add_dialog.btnList = [];
      this.is_preview = true;
      this.getById(id, true);
    },
    // 跳转预警通知单/响应命令单
    toResponse(row) {
      const name = row.dutyCategory == 1 ? "NoticeDetail" : "EmergencyResponseinfo";
      this.$router.push({
        name,
        query: {
          id: row.dutySourceId
        }
      });
    },
    // 获取某个日期的下一个日期
    getNowNextDate(date) {
      var d = new Date(date);
      d.setDate(d.getDate() + 1);
      return this.formatDate(d);
    },
    formatDate(val) {
      const d = new Date(val);
      const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
      const date = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
      return `${d.getFullYear()}-${month}-${date}`;
    }
  }
};
</script>

<style lang='less' scoped>
@import "../../../../assets/style/common.less";
@import "../../../../assets/style/ComponentStyle.less";
@import "../../../../assets/style/pop-upNotification.less";

.font-s-16 {
  font-size: 16px;
  color: #606266;
}

:deep(.el-breadcrumb__inner.is-link) {
  font-weight: 100;
  color: #fff;
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #3270ff;
}

:deep(.el-descriptions-item__label:not(.is-bordered-label)) {
  margin-right: 5px;
}

.box {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin-top: 15px;
  background-color: #fff;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
}

:deep(.el-form-item__label) {
  font-size: 16px;
}

:deep(.el-date-editor--daterange.el-input__inner) {
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  padding: 0 20px;
}

.blue-text {
  color: #3270ff;
  text-decoration: underline;
  cursor: pointer;
}

.change-icon {
  width: 30px;
  height: 30px;
  cursor: pointer;

  &+.change-icon {
    margin-left: 20px;
  }
}

.leave-icon {
  width: 20px;
  height: 20px;
  vertical-align: middle;
}

:deep(.el-range-input) {
  font-size: 16px;
}

:deep(.el-select),
:deep(.el-date-editor.el-input) {
  width: 100%;
}

// :deep(.approve-form) {
//   .sjgy {
//     .el-form-item__content {
//       // display: block;
//       // width: 100%;
//       flex: 1;
//     }
//   }
// }

:deep(.change-person-cell) {
  padding: 7px 0;
}

:deep(.staff-col) {
  padding: 0;

  .cell {
    padding: 0;

    .staff-cell {
      height: 50px;
      line-height: 50px;
      border-right: 1px solid#EBEEF5;
      margin-right: -1px;
      border-bottom: 1px solid#EBEEF5;
      margin-bottom: -1px;
      box-sizing: border-box;
    }
  }
}

:deep(.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before) {
  display: inline-block;
  font-size: 28px;
  position: relative;
  top: 10px;
  margin-top: -10px;
}

:deep(.is-preview) {
  .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
    color: transparent;
  }
}

:deep(.duty-leaders) {
  .el-input {
    font-size: 16px;
  }

  .el-select-dropdown__item {
    text-align: left;
  }
}

:deep(.leave-table) {
  th {
    .cell {
      padding: 0 !important;
    }
  }
}

.leaveForm {
  :deep(.el-form-item) {
    margin-right: 5px;
  }

  .operateImg {
    >img {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }
  }
}

.importDialog {
  :deep(.el-dialog) {
    height: 200px;

    .el-dialog__body {
      margin-top: 20px;
      height: auto;
      overflow-y: initial;
    }
  }
}

.footer {
  display: flex;
  justify-content: center;
}
</style>
